﻿using System;
using System.Linq;
using System.Windows.Forms;

namespace Nautilus_Password_Reset {

	public partial class Form1 : Form {

		public Form1() {
			InitializeComponent();
		}

		private void SubmitButton_Click(object sender, EventArgs e) {

			/*
			 * Validate user input.
			 */

			string errorMessage = String.Empty;
			string email = EmailTextBox.Text.Trim();
			if (String.IsNullOrEmpty(email)) {
				errorMessage += "* Please enter an email address.\n";
			}
			string password = PasswordTextBox.Text.Trim();
			if (String.IsNullOrEmpty(password)) {
				errorMessage += "* Please enter an email address.\n";
			}
			string environment = EnvironmentComboBox.Text;
			if (environment == "-- Select --") {
				errorMessage += "* Please select an environment.";
			}
			if (errorMessage != String.Empty) {
				MessageBox.Show(this, errorMessage);
				return;
			}

			/*
			 * No errors, so update the salt and password.
			 */

			try {
				string passwordSalt = Cryptography.CreateRandomString(32);
				string passwordHash = Cryptography.HashPassword(passwordSalt, password);
				switch (EnvironmentComboBox.Text) {
					case "Dev":
						using (DevDeytaNautilusEntities db = new DevDeytaNautilusEntities()) {
							SiteUser siteUser = db.SiteUsers.SingleOrDefault(x => x.EmailAddress == email);
							if (siteUser != null) {
								siteUser.PasswordSalt = passwordSalt;
								siteUser.PasswordHash = passwordHash;
								siteUser.IsLocked = false;
								siteUser.FailedLoginAttempts = 0;
								db.SaveChanges();
							}
						}
						break;
					case "QA":
						using (QaDeytaNautilusEntities db = new QaDeytaNautilusEntities()) {
							SiteUser siteUser = db.SiteUsers.SingleOrDefault(x => x.EmailAddress == email);
							if (siteUser != null) {
								siteUser.PasswordSalt = passwordSalt;
								siteUser.PasswordHash = passwordHash;
								siteUser.IsLocked = false;
								siteUser.FailedLoginAttempts = 0;
								db.SaveChanges();
							}
						}
						break;
				}
				MessageBox.Show("Password reset.");
			} catch {
				MessageBox.Show("Failed to reset password.");
			}
		}

	}

}